package org.gdstash.character;

import org.gdstash.file.GDReader;
import org.gdstash.file.GDWriter;
import org.gdstash.util.FileVersionException;
import org.gdstash.util.GDMsgFormatter;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class GDCharTutorialList {
    private static final int VERSION = 1;
    private static final int BLOCK = 15;
    public static final int TUTORIAL_DEATH = 23;
    private int version;
    private List<Integer> pages;

    public GDCharTutorialList() {
        this.pages = new LinkedList<Integer>();
    }

    public void addTutorial(final int page) {
        boolean found = false;
        for (final int i : this.pages) {
            if (i == page) {
                found = true;
                break;
            }
        }
        if (!found) {
            this.pages.add(page);
        }
    }

    public void removeTutorial(final int page) {
        final Iterator<Integer> iter = this.pages.iterator();
        while (iter.hasNext()) {
            final int i = iter.next();
            if (i == page) {
                iter.remove();
                break;
            }
        }
    }

    public void read() throws IOException {
        int val = 0;
        final GDReader.Block block = new GDReader.Block();
        val = GDReader.readBlockStart(block);
        if (val != 15) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.version = GDReader.readEncInt(true);
        if (this.version != 1) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.pages.clear();
        val = GDReader.readEncInt(true);
        for (int i = 0; i < val; ++i) {
            final int page = GDReader.readEncInt(true);
            this.pages.add(page);
        }
        GDReader.readBlockEnd(block);
    }

    public void write() throws IOException {
        final GDReader.Block block = new GDReader.Block();
        GDWriter.writeBlockStart(block, 15);
        GDWriter.writeInt(this.version);
        final int val = this.pages.size();
        GDWriter.writeInt(val);
        for (final int page : this.pages) {
            GDWriter.writeInt(page);
        }
        GDWriter.writeBlockEnd(block);
    }

    public int getByteSize() {
        int size = 0;
        size += 4;
        size += 4;
        size += 4;
        size += 4;
        size += 4 * this.pages.size();
        size += 4;
        return size;
    }
}
